//
//  UIImage+CAIDraw.m
//  CAICategories
//
//  Created by 海参 on 2022/9/19.
//

#import "UIImage+CAIDraw.h"

@implementation UIImage (CAIDraw)

+ (UIImage *)caiImageOfDashLineWithStrokeColor:(UIColor *)strokeColor
                                     lineWidth:(nullable NSNumber *)lineWidth
                                   patternDash:(int)dashLength
                                    patternGap:(int)gapLength
                                    boundsSize:(CGSize)size
                        lineDirectionHorizonal:(BOOL)isHorizonal
{
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGFloat lineW = lineWidth ? [lineWidth floatValue]:1;
    CGFloat dash = MAX(5, dashLength);
    CGFloat gap = MAX(1, gapLength);
    if (!isHorizonal) {
        CGFloat pointX = rect.size.width/2-lineW/2;
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextSetLineCap(ctx, kCGLineCapRound);
        CGContextSetStrokeColorWithColor(ctx, strokeColor.CGColor);
//        NSInteger section  = rect.size.height/(dash + gap);
//        CGFloat lineDash[section];
//        for (int i = 0; i<section; i++) {
//            if (i%2 == 0) {
//                lineDash[i] = dash;
//            }else{
//                lineDash[i] = gap;
//            }
//        }
//        CGContextSetLineDash(ctx, 0, lineDash, section);
        CGContextSetLineWidth(ctx,lineW);
        /// 设置虚线的线段长度 和 间隙长度，重复指定。 这个C数组应该是全部数据
        ///实际测试，即使只有2条，也会绘制到终点为止。待研究UIbezierPath的虚线
        CGFloat lineDash[] = {dash,gap};
        /// 这个应该是lengths的数组长度，怎么是2？
        CGContextSetLineDash(ctx, 0, lineDash, 2);
        ///为什么还要用moveToPoint，AddLine添加一条直线，strokePath绘制线？
        CGContextMoveToPoint(ctx, pointX,0.0);
        CGContextAddLineToPoint(ctx, pointX,size.height);
        CGContextStrokePath(ctx);
        return UIGraphicsGetImageFromCurrentImageContext();
    }
    CGFloat pointY = rect.size.height/2-lineW/2;
    // 获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetLineCap(ctx, kCGLineCapRound);
    CGContextSetStrokeColorWithColor(ctx, strokeColor.CGColor);
    CGContextSetLineWidth(ctx,lineW);
    CGFloat lineDash[] = {dash,gap};
    CGContextSetLineDash(ctx, 0, lineDash, 2);
    CGContextMoveToPoint(ctx, 0.0, pointY);
    CGContextAddLineToPoint(ctx, size.width, pointY);
    CGContextStrokePath(ctx);
    return UIGraphicsGetImageFromCurrentImageContext();
}


@end
